package xyz.labmem.app.util

import cn.hutool.core.thread.ExecutorBuilder
import cn.hutool.log.StaticLog
import javafx.application.Platform
import javafx.beans.property.SimpleDoubleProperty
import javafx.event.EventHandler
import javafx.scene.Node
import javafx.scene.input.MouseEvent
import javafx.stage.Stage
import javafx.stage.Window
import xyz.labmem.app.config.AppConfig.mouseImage
import xyz.labmem.util.viewRun
import java.util.concurrent.ExecutorService
import kotlin.system.exitProcess


fun Stage.dragWin(
    node: Node,
    xc: SimpleDoubleProperty = SimpleDoubleProperty(0.0),
    yc: SimpleDoubleProperty = SimpleDoubleProperty(0.0)
) {
    var bX = 0.0
    var yx = 0.0
    node.setOnMouseDragged {
        this.x = it.screenX - bX - xc.value
        this.y = it.screenY - yx - yc.value
    }
    node.setOnMousePressed {
        bX = it.x
        yx = it.y
    }
}

fun changeCursors(type: String, vararg nodes: Node?) {
    for (node in nodes) {
        node?.changeCursors(type)
    }
}

fun Node.changeCursors(type: String) {
    this.onMouseEntered = EventHandler {
        this.cursor = mouseImage[type]
    }
}

fun Window.close(closeBefore: (() -> Unit)? = null) {
    closeBefore?.let { it() }
    StaticLog.info(">>>>>LabFXApp--完全关闭")
    Platform.exit()
    exitProcess(0)
}

private val mouseClickedExecutor: ExecutorService = ExecutorBuilder.create()
    .setCorePoolSize(1)
    .setMaxPoolSize(1)
    .setKeepAliveTime(0)
    .build()

fun mouseClickedPoll(f: (MouseEvent) -> Unit): EventHandler<MouseEvent> {
    return EventHandler<MouseEvent> {
        mouseClickedExecutor.execute {
            viewRun { f(it)}
        }
    }
}